<template>
  <div class="company-review">
    
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="公司名称">
          <el-input v-model="searchForm.companyName" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="统一社会信用代码">
          <el-input v-model="searchForm.creditCode" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="认证状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 200px;">
            <el-option label="全部" value="" />
            <el-option label="待提交" value="unsubmitted" />
            <el-option label="待审核" value="pending_review" />
            <el-option label="已通过" value="approved" />
            <el-option label="已驳回" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>企业认证列表</span>
          <el-button type="primary" @click="handleRefresh">刷新</el-button>
        </div>
      </template>
      
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="companyName" label="公司全称" min-width="20%">
          <template #default="scope">
            <el-button link @click="handleViewDetail(scope.row)">
              {{ scope.row.companyName }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="creditCode" label="统一社会信用代码" min-width="25%" />
        <el-table-column prop="submitTime" label="提交时间" min-width="20%" />
        <el-table-column prop="status" label="状态" min-width="15%">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="20%">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleApprove(scope.row)">
              认证通过
            </el-button>
            <el-button type="danger" size="small" @click="handleReject(scope.row)">
              认证驳回
            </el-button>
            <el-button type="info" size="small" @click="handleViewDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="企业认证详情"
      width="70%"
    >
      <div v-if="currentDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="企业ID">{{ currentDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="企业用户ID">{{ currentDetail.enterpriseUserId }}</el-descriptions-item>
          <el-descriptions-item label="公司全称">{{ currentDetail.companyName }}</el-descriptions-item>
          <el-descriptions-item label="统一社会信用代码">{{ currentDetail.creditCode }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentDetail.phone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ currentDetail.email }}</el-descriptions-item>
          <el-descriptions-item label="运营者姓名">{{ currentDetail.operatorName }}</el-descriptions-item>
          <el-descriptions-item label="运营者职位">{{ currentDetail.operatorPosition }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ currentDetail.submitTime }}</el-descriptions-item>
          <el-descriptions-item label="认证状态">
            <el-tag :type="getStatusType(currentDetail.status)">
              {{ getStatusText(currentDetail.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 证照信息 -->
        <div class="detail-section" v-if="currentDetail.licenseImage || currentDetail.companyLogo">
          <h4 style="margin-bottom: 20px; color: #2c3e50; font-size: 18px; font-weight: 600;">证照信息</h4>
          <div class="certificates-container">
            <!-- 营业执照 -->
            <div class="certificate-item license-section">
              <h5 class="certificate-title">营业执照</h5>
              <div class="license-wrapper">
                <el-image
                  v-if="currentDetail.licenseImage"
                  :src="currentDetail.licenseImage"
                  fit="contain"
                  class="license-image-display"
                />
                <div v-else class="no-image-placeholder">
                  <i class="el-icon-picture"></i>
                  <span>暂无营业执照</span>
                </div>
              </div>
            </div>
            
            <!-- 公司Logo -->
            <div class="certificate-item logo-section">
              <h5 class="certificate-title logo-title">公司Logo</h5>
              <div class="logo-wrapper">
                <el-image
                  v-if="currentDetail.companyLogo"
                  :src="currentDetail.companyLogo"
                  fit="contain"
                  class="logo-image-display"
                />
                <div v-else class="no-image-placeholder">
                  <i class="el-icon-picture"></i>
                  <span>暂无公司Logo</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="detail-section" v-if="currentDetail.rejectionReason">
          <h4>驳回理由</h4>
          <p style="color: #f56c6c;">{{ currentDetail.rejectionReason }}</p>
        </div>
      </div>
    </el-dialog>
    
    <!-- 驳回对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="驳回认证"
      width="40%"
    >
      <el-form :model="rejectForm" label-width="80px">
        <el-form-item label="驳回理由" required>
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入驳回理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmReject">确认驳回</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getEnterpriseCertificationList, getEnterpriseCertificationListByStatus, getEnterpriseCertificationDetail, approveEnterpriseCertification, rejectEnterpriseCertification } from '@/api/enterpriseCertification'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const detailDialogVisible = ref(false)
const rejectDialogVisible = ref(false)
const currentDetail = ref(null)

const searchForm = reactive({
  companyName: '',
  creditCode: '',
  status: '',
  dateRange: []
})

const rejectForm = reactive({
  reason: ''
})

const tableData = ref([])

// 获取企业认证列表
const fetchEnterpriseList = async () => {
  try {
    loading.value = true
    let response
    
    if (searchForm.status) {
      // 如果有状态筛选，调用状态筛选接口
      response = await getEnterpriseCertificationListByStatus(searchForm.status, {
        page: currentPage.value,
        size: pageSize.value
      })
    } else {
      // 否则调用普通列表接口
      response = await getEnterpriseCertificationList({
        page: currentPage.value,
        size: pageSize.value
      })
    }
    
    if (response.code === 200) {
      tableData.value = response.data.enterprises.map(item => ({
        id: item.enterprise_id,
        companyName: item.company_full_name,
        creditCode: item.social_credit_code,
        submitTime: new Date(item.submit_time).toLocaleString('zh-CN'),
        status: item.certification_status
      }))
      
      total.value = response.data.totalCount
      currentPage.value = response.data.currentPage
      pageSize.value = response.data.pageSize
    } else {
      ElMessage.error(response.message || '获取企业认证列表失败')
    }
  } catch (error) {
    ElMessage.error('获取企业认证列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

const getStatusType = (status) => {
  const statusMap = {
    unsubmitted: 'info',
    pending_review: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    unsubmitted: '待提交',
    pending_review: '待审核',
    approved: '已通过',
    rejected: '已驳回'
  }
  return statusMap[status] || '未知'
}

const handleSearch = () => {
  currentPage.value = 1
  fetchEnterpriseList()
}

const handleReset = () => {
  searchForm.companyName = ''
  searchForm.creditCode = ''
  searchForm.status = ''
  searchForm.dateRange = []
  currentPage.value = 1
  fetchEnterpriseList()
}

const handleRefresh = () => {
  fetchEnterpriseList()
}

const handleViewDetail = async (row) => {
  try {
    const response = await getEnterpriseCertificationDetail(row.id)
    
    if (response.code === 200) {
      currentDetail.value = {
        id: response.data.enterprise_id,
        enterpriseUserId: response.data.enterprise_user_id,
        companyName: response.data.company_full_name,
        creditCode: response.data.social_credit_code,
        phone: response.data.contact_phone_number,
        email: response.data.contact_email,
        operatorName: response.data.operator_name,
        operatorPosition: response.data.operator_position,
        // 修改这里：为图片URL添加环境变量前缀
        licenseImage: response.data.business_license_url ? `${__API_BASE_URL__}${response.data.business_license_url}` : null,
        submitTime: new Date(response.data.submit_time).toLocaleString('zh-CN'),
        status: response.data.certification_status,
        rejectionReason: response.data.certification_rejection_reason
      }
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取企业详情失败')
    }
  } catch (error) {
    ElMessage.error('获取企业详情失败，请检查网络连接')
  }
}

const handleApprove = (row) => {
  ElMessageBox.confirm(
    '确定要通过该企业的认证申请吗？',
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await approveEnterpriseCertification(row.id)
      if (response.code === 200) {
        ElMessage.success('企业认证已通过')
        fetchEnterpriseList() // 刷新列表
      } else {
        ElMessage.error(response.message || '操作失败')
      }
    } catch (error) {
      ElMessage.error('操作失败，请重试')
    }
  })
}

const handleReject = (row) => {
  currentDetail.value = row
  rejectForm.reason = ''
  rejectDialogVisible.value = true
}

const handleConfirmReject = async () => {
  if (!rejectForm.reason.trim()) {
    ElMessage.warning('请输入驳回理由')
    return
  }
  
  try {
    const response = await rejectEnterpriseCertification(currentDetail.value.id, rejectForm.reason)
    if (response.code === 200) {
      ElMessage.success('企业认证已驳回')
      rejectDialogVisible.value = false
      fetchEnterpriseList() // 刷新列表
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败，请重试')
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchEnterpriseList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchEnterpriseList()
}

onMounted(() => {
  fetchEnterpriseList()
})
</script>

<style scoped>
.company-review {
  padding: 20px;
  width: 100%;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: #f5f5f5;
}

.company-review h2 {
  margin-bottom: 20px;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.search-card {
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 0;
}

.table-card {
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
}

/* 表格样式优化 */
:deep(.el-table) {
  width: 100% !important;
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .cell) {
  padding: 0 12px;
}

/* 表格列宽度优化 */
:deep(.el-table .el-table__column) {
  min-width: 120px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
  padding: 10px 0;
}

.detail-section {
  margin-top: 20px;
}

.detail-section h4 {
  margin-bottom: 10px;
  color: #333;
  font-weight: 600;
}

.detail-section p {
  color: #666;
  line-height: 1.6;
  margin: 0;
}

.image-container {
  margin-top: 10px;
}

/* 移除按钮边框 */
:deep(.el-button--link) {
  border: none !important;
  outline: none !important;
}

:deep(.el-button--link:focus) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}

:deep(.el-button--link:hover) {
  border: none !important;
  outline: none !important;
}

/* 移除普通按钮的边框 */
:deep(.el-button:focus) {
  outline: none !important;
  box-shadow: none !important;
}

/* 确保下拉框文字显示 */
:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input__inner) {
  color: #606266;
}

:deep(.el-select .el-input__inner::placeholder) {
  color: #c0c4cc;
}

/* 图片容器样式 - 重新设计 */
.images-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-top: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e9ecef;
}

.image-item {
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.image-item:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.image-item h5 {
  margin: 0 0 12px 0;
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
  text-align: center;
  padding-bottom: 8px;
  border-bottom: 2px solid #3498db;
}

/* 营业执照样式 - 重新设计 */
.license-image-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  background: #ffffff;
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 16px;
  transition: border-color 0.3s ease;
}

.license-image-wrapper:hover {
  border-color: #3498db;
}

.license-image {
  max-width: 100%;
  max-height: 300px;
  width: auto;
  height: auto;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.3s ease;
}

.license-image:hover {
  transform: scale(1.02);
}

/* 公司Logo样式 - 重新设计 */
.logo-image-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  background: #ffffff;
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 20px;
  transition: border-color 0.3s ease;
}

.logo-image-wrapper:hover {
  border-color: #e74c3c;
}

.logo-image {
  max-width: 150px;
  max-height: 150px;
  width: auto;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.3s ease;
}

.logo-image:hover {
  transform: scale(1.05);
}

/* 无图片时的占位样式 */
.no-image-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  color: #999;
  font-size: 14px;
  background: #f8f9fa;
  border: 2px dashed #ddd;
  border-radius: 8px;
}

.no-image-placeholder i {
  font-size: 48px;
  margin-bottom: 12px;
  color: #ccc;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .images-container {
    grid-template-columns: 1fr;
    gap: 16px;
    padding: 16px;
  }
  
  .image-item {
    padding: 12px;
  }
  
  .license-image {
    max-height: 250px;
  }
  
  .logo-image {
    max-width: 120px;
    max-height: 120px;
  }
}

@media (max-width: 480px) {
  .images-container {
    padding: 12px;
  }
  
  .license-image {
    max-height: 200px;
  }
  
  .logo-image {
    max-width: 100px;
    max-height: 100px;
  }
}

/* 新的证照信息样式 */
.certificates-container {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e9ecef;
}

.certificate-item {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.certificate-title {
  margin: 0 0 16px 0;
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
  text-align: center;
  padding-bottom: 8px;
  border-bottom: 2px solid #3498db;
}

.logo-title {
  border-bottom-color: #e74c3c;
}

.license-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background: #ffffff;
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 16px;
  flex: 1;
}

.logo-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  background: #ffffff;
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 16px;
  flex: 1;
}

.license-image-display {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.license-image-display:hover {
  transform: scale(1.02);
}

.logo-image-display {
  max-width: 160px;
  max-height: 160px;
  width: auto;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.logo-image-display:hover {
  transform: scale(1.05);
}

.no-image-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
  font-size: 14px;
}

.no-image-placeholder i {
  font-size: 48px;
  margin-bottom: 12px;
  color: #ccc;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .certificates-container {
    grid-template-columns: 1fr;
    gap: 16px;
    padding: 16px;
  }
  
  .license-wrapper {
    min-height: 300px;
  }
  
  .logo-wrapper {
    min-height: 180px;
  }
}
</style>